package com.ycode.demo.controller;

import com.ycode.demo.model.User;
import com.ycode.demo.service.UserService;
import com.ycode.demo.service.exception.UserAlreadyExistsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>Title: UserController.java </p>
 * <p>Description: </p>
 * <p>Company: Snail Game </p>
 *
 * @author Xinying Ge
 * @date: 05/08/2014
 * @time: 13:56
 */
@RestController
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    private final UserService userService;

    @Inject
    public UserController(final UserService userService) {
        this.userService = userService;
    }

//    @InitBinder("form")
//    public void initBinder(WebDataBinder binder) {
//        binder.addValidators(passwordValidator);
//    }

    @RequestMapping(value = "/user",
            method = RequestMethod.POST,
            headers = {"Content-type=application/json"})
    public User createUser(@RequestBody @Valid final User user) {
        LOGGER.debug("Received request to create the {}", user);
//        request.getParameterMap().keySet();
        return userService.save(user);
    }

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public List<User> listUsers() {
        LOGGER.debug("Received request to list all users");
        return userService.getList();
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.CONFLICT)
    public String handleUserAlreadyExistsException(UserAlreadyExistsException e) {
        return e.getMessage();
    }
}
